package com.portal.incurridos.persistence.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;

import com.portal.incurridos.persistence.dao.LabeledDao;
import com.portal.incurridos.persistence.enumeration.StateTransactionEnum;
import com.portal.incurridos.persistence.wall.Labeled;

/**
 * @author Alan Dávila
 * e-mail ustargab@gmail.com
 * date 29/11/2013 00:02:52
 */
@Component("labeledDaoImpl")
public class LabeledDaoHibernateImpl implements LabeledDao {

	/**
	 * Managment bean of dao layer.
	 */
	@Resource(name = "sessionFactory")
    private SessionFactory factoria;

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.LabeledDao#get(java.lang.Long)
	 */
	@SuppressWarnings("unchecked")
	public final List<Labeled> get(final Long card) {
		Session session = null;
		List<Labeled> listLabeled = null;
		try {
			session = factoria.getCurrentSession();
			listLabeled = session.createQuery("from Labeled where card = ?")
					.setLong(1, card)
					.list();
			session.close();
		} catch (Exception e) {
			listLabeled = new ArrayList<Labeled>();
		}
		return listLabeled;
	}

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.LabeledDao#create(java.lang.Long, java.lang.Integer)
	 */
	public final StateTransactionEnum create(final Labeled labeled) {
		Session session = null;
		Transaction tx = null;
		try {
			session = factoria.getCurrentSession();
			tx = session.beginTransaction();
			session.save(labeled);
			session.close();
		} catch (Exception e) {
			return StateTransactionEnum.ERROR;
		}
		return StateTransactionEnum.NEW;
	}

	/* (non-Javadoc)
	 * @see com.portal.incurridos.persistence.dao.LabeledDao#delete(java.lang.Long, java.lang.Integer)
	 */
	public final StateTransactionEnum delete(final Labeled labeled) {
		Session session = null;
		Transaction tx = null;
		try {
			session = factoria.getCurrentSession();
			tx = session.beginTransaction();
			session.delete(labeled);
			session.close();
		} catch (Exception e) {
			return StateTransactionEnum.ERROR;
		}
		return StateTransactionEnum.DELETED;
	}

}
